const express = require('express');
const router = express.Router();
const { User } = require('../models');
const UserController = require('../controllers/users');
const userController = new UserController();

// 获取所有用户
router.get('/', (req, res) => userController.getAllUsers(req, res));

// 获取单个用户
router.get('/:id', async (req, res, next) => {
  try {
    const user = await User.findByPk(req.params.id, {
      attributes: ['id', 'nick_name', 'avatar_url', 'is_active', 'created_at']
    });

    if (!user) {
      return res.status(404).json({
        status: 'error',
        error: {
          code: 'USER_NOT_FOUND',
          message: '用户不存在',
          details: `未找到ID为 ${req.params.id} 的用户`
        }
      });
    }

    res.json(user);
  } catch (err) {
    next(err);
  }
});

// 创建用户
router.post('/', async (req, res, next) => {
  try {
    // 检查nick_name是否提供
    if (!req.body.nick_name) {
      return res.status(400).json({
        status: 'error',
        error: {
          code: 'MISSING_REQUIRED_FIELD',
          message: '缺少必填字段',
          details: 'nick_name是必填字段'
        }
      });
    }

    // 验证nick_name长度
    if (req.body.nick_name.length > 50) {
      return res.status(400).json({
        status: 'error',
        error: {
          code: 'INVALID_FIELD_LENGTH',
          message: '字段长度无效',
          details: 'nick_name长度不能超过50个字符'
        }
      });
    }

    // 创建用户
    const user = await User.create({
      nick_name: req.body.nick_name,
      avatar_url: req.body.avatar_url,
      openid: req.body.openid,
      is_active: req.body.is_active || 1
    });

    res.status(201).json({
      id: user.id,
      nick_name: user.nick_name,
      avatar_url: user.avatar_url,
      openid: user.openid,
      is_active: user.is_active,
      created_at: user.created_at,
      updated_at: user.updated_at
    });
  } catch (err) {
    // 处理唯一约束错误
    if (err.name === 'SequelizeUniqueConstraintError') {
      return res.status(409).json({
        status: 'error',
        error: {
          code: 'DUPLICATE_ENTRY',
          message: '数据已存在',
          details: 'openid必须是唯一的'
        }
      });
    }

    // 处理其他错误
    res.status(500).json({
      status: 'error',
      error: {
        code: 'INTERNAL_SERVER_ERROR',
        message: '服务器内部错误',
        details: err.message
      }
    });
  }
});

// 更新用户
router.put('/:id', async (req, res, next) => {
  try {
    const [updated] = await User.update({
      nick_name: req.body.nick_name,
      avatar_url: req.body.avatar_url,
      is_active: req.body.is_active
    }, {
      where: { id: req.params.id }
    });

    if (updated) {
      const user = await User.findByPk(req.params.id, {
        attributes: ['id', 'nick_name', 'avatar_url', 'is_active']
      });
      return res.json(user);
    }

    res.status(404).json({
      status: 'error',
      error: {
        code: 'USER_NOT_FOUND',
        message: '用户不存在',
        details: `未找到ID为 ${req.params.id} 的用户`
      }
    });
  } catch (err) {
    next(err);
  }
});

// 删除用户
router.delete('/:id', async (req, res, next) => {
  try {
    const deleted = await User.destroy({
      where: { id: req.params.id }
    });

    if (deleted) {
      return res.status(204).end();
    }

    res.status(404).json({
      status: 'error',
      error: {
        code: 'USER_NOT_FOUND',
        message: '用户不存在',
        details: `未找到ID为 ${req.params.id} 的用户`
      }
    });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
